package com.jpatest.demo.Service;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.x.discovery.ServiceDiscovery;
import org.apache.curator.x.discovery.ServiceDiscoveryBuilder;
import org.apache.curator.x.discovery.ServiceInstance;
import org.apache.curator.x.discovery.details.JsonInstanceSerializer;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.TimeUnit;

//@Service
public class OrderServiceImpl{
    private org.slf4j.Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    CuratorFramework client;
    String lockPath = "/lock/order";

    public void makeOrderType(String type){
        String path = lockPath + type;
        log.info("try do job for"+ type);
        try {
            findService(client,type);
            InterProcessMutex lock = new InterProcessMutex(client,path);
            if(lock.acquire(10, TimeUnit.HOURS)){
                try{
                    Thread.sleep(1000*5);
                    log.info("do job "+type+ "done");
                }
                finally {
                    lock.release();
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void testZKService(String serviceName){
        try {
            findService(client,serviceName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected ServiceInstance<Map> findService(CuratorFramework client,String serviceName) throws Exception{
        ServiceDiscovery<Map> serviceDiscovery = ServiceDiscoveryBuilder.builder(Map.class).client(client).serializer(new JsonInstanceSerializer<Map>(Map.class)).basePath("/service").build();
        serviceDiscovery.start();
        //取得当前所有的服务
        Collection<ServiceInstance<Map>> all = serviceDiscovery.queryForInstances(serviceName);
        if(all.size()==0){
            return null;
        }else{
            //取得第一个服务
            ServiceInstance<Map> service = new ArrayList<ServiceInstance<Map>>(all).get(0);
            System.out.println(service.getAddress());
            System.out.println(service.getPayload());
            return service;
        }
    }
}
